var urllib = require('urllib');
var util = require('util');
var QRCodetorul = require("qrcode");
var crypto = require('crypto');
var url = require('url');
var qs = require('qs');
var _ = require('underscore');
var path = require('path');
const fs = require('fs');
const { wechat, MYSQL_CONF } = require('../../server_config.json')
var { init, format } = require('../models/people');
const { Add, Update, ExecSqlparmater, ExecGetOne, Query, Exec, QueryOne } = require('../db/dbhelper');
const { usertokenAdd, usertokenGetInfo, usertokenUpdate } = require('./usertoken');
const { decryptData, requestGet, requestPost, formatDate, formatDateTime, MathCode } = require('../libs/common');
var { SendWechatMsg, getToken, getUserUnionid, queryUserList, queryUserInfo } = require('../libs/tencent_cloud');
var { qrcodeAdd, qrcodeQueryOne, qrcodeUpdate } = require('./qrcode');
var put_local = require('./ossfile').put_local;
const logger = require('../libs/log').logger;
const { messageAdd, messageUpdate } = require('./message');
const { sendmsg_sms } = require('../libs/sms');
const { msgsubscribeIsRead, msgsubscribeAdd, msgsubscribeUpdate, msgsubscribeEdit } = require('./msgsubscribe');
const { isOfficial, wechatuserAdd, wechatuserQuery, wechatuserUpdate } = require('./wechatuser');
const isactive = require('./setting').isactive;
var { buildQrcode } = require('./qrcode');
var moment = require('moment');

async function peopleExecOne(filter, select) {
  return QueryOne('hzz_peoples', filter, select);
}
async function getOpenid(doc) {
  try {
    logger.info('-----getOpenid----doc:', doc);
    if (!doc.appcode) {
      return {
        code: 1,
        msg: 'appcode参数不能为空'
      }
    }
    //格式化请求地址
    var url = util.format(wechat.sessionUrl, wechat.appid, wechat.appsecret, doc.appcode, "authorization_code");

    var result = await requestGet(url);
    if (result && result.openid) {
      // 返回用户登录态key随机子串
      let creobj = {
        openid: result.openid,
        appcode: doc.appcode,
        session_key: result.session_key,
        unionid: result.unionid,
        remarks: '用户登录获取'
      };
      let sql_token = `SELECT * FROM hzz_usertokens  WHERE openid = '${result.openid}'`;
      let token_user = await ExecGetOne(sql_token);

      if (token_user) {
        let peo = await peopleExecOne({ code: token_user.pcode }, 'id,code,isfirst,avator,nickname');
        if (!peo) {
          return {
            code: 1,
            msg: '程序异常，请联系客服'
          }
        }
        creobj.id = token_user.id;
        await usertokenUpdate(creobj);
        let isOfficial = await getOfficial(creobj);
        let rdata = {
          code: 0,
          data: {
            'pcode': token_user.pcode
            , 'isfirst': peo.isfirst, 'isOfficial': isOfficial, avator: peo.avator, nickname: peo.nickname
          }
        }
        logger.info('-----getOpenid----rdata:', rdata);
        return rdata;
      } else {
        let invister;
        doc.ycode = doc.ycode ? doc.ycode : '818159500119';// 没有推荐人默认给文叔 
        if (doc.ycode) {
          invister = await peopleExecOne({ code: doc.ycode }, 'code,phone,inviter_wechat_code,invitcode,isinviter,inviter_code');
        }
        // 创建用户信息
        let onk = {
          openid: result.openid
        };
        if (invister) {
          if (invister.isinviter) { // 邀请人是推荐人，被邀请人的邀请人绑定为邀请人的推荐人
            onk.invitcode = invister.code;
            onk.inviter_wechat_code = invister.phone ? invister.phone : wechat.invister_phone;
            onk.inviter_code = invister.invitcode;
          } else { // 邀请人不是推荐人，被邀请人继承邀请人的推荐人信息
            onk.invitcode = invister.invitcode;
            onk.inviter_wechat_code = invister.inviter_wechat_code ? invister.inviter_wechat_code : wechat.invister_phone;
            onk.inviter_code = invister.code;
          }
        }
        logger.info('-----getOpenid---创建新用户:onk', onk);
        let new_onk = init(onk)
        logger.info('-----getOpenid---创建新用户:new_onk', new_onk);
        let peo_new = await Add('hzz_peoples', new_onk);
        // 获取用户unionid
        creobj.pcode = peo_new.code;
        token_user = await usertokenAdd(creobj);
        let isOfficial = await getOfficial(token_user);
        // logger.info('-----getOpenid---return:', JSON.stringify({ 'pcode': peo_new.code, 'isfirst': 1, 'isOfficial': isOfficial,'token_user':token_user, avator: peo_new.avator, nickname: peo_new.nickname }));
        return {
          code: 0,
          data: {
            'pcode': peo_new.code
            , 'isfirst': 1, 'isOfficial': isOfficial, avator: peo_new.avator, nickname: peo_new.nickname
          }
        }
      }
    } else {
      return {
        code: 1,
        msg: '获取微信openid失败,请联系客服'
      }
    }
  } catch (error) {
    logger.error('getOpenid', doc, error);
    return {
      code: 1,
      msg: error ? error.message : '获取openid异常,请联系客服'
    }
  }
}
async function First(pcode) {
  try {
    logger.info('First pcode--: ', pcode)
    if (!pcode) {
      return {
        code: 1,
        msg: 'pcode不允许为空！'
      };
    }
    let data = {
      isactive: false
    };
    let result = {};
    let tokenData = await usertokenGetInfo(pcode)
    if (tokenData) {
      let { unionid, openid } = tokenData;
      if (!unionid) {
        unionid = await getUserUnionid(openid);
      }
      let isOff = await isOfficial(unionid);
      let people = await peopleExecOne({ code: pcode }, 'code,isfirst,avator,nickname');
      data.isOfficial = isOff;
      data = _.extend(data, people);
      // 首页是否展示活动
      data.isactive = await isactive();
      result = {
        code: 0,
        data: data,
        msg: '获取信息成功'
      }
    } else {
      return {
        code: 1,
        msg: '用户已注销'
      };
    }
    logger.info('First pcode--result: ', result)
    return result;
  } catch (error) {
    logger.error('First pcode--error: ', error)
    return {
      code: 1,
      msg: '用户身份信息获取失败,请联系客服'
    }
  }
}
async function decodeDataInfo(pcode, encryptedData, iv) {
  if (!pcode) {
    return {
      code: 1,
      msg: 'pcode不允许为空！'
    };
  }
  let tokendata = await usertokenGetInfo(pcode);
  if (tokendata) {
    var data = decryptData(tokendata.session_key, encryptedData, iv);

    logger.info('解密后 data: ', data)
    // await peopleSave({ phone: data.phone, openid: tokendata.openid, appcode: tokendata.appcode, session_key: tokendata.session_key, token: token });
    return {
      code: 0,
      msg: '解密成功',
      data: data
    };
  } else {
    return {
      code: 1,
      msg: 'token信息未找到,解密失败'
    }
  }

}

// 生成带参小程序二维码
async function mybuildqrcode(pcode) {
  if (!pcode) {
    return {
      code: 1,
      msg: 'pcode不允许为空！'
    };
  }
  const isexist = await qrcodeQueryOne({ pcode: pcode });
  if (!isexist || !isexist.url) {
    let url = wechat.qrcodeurl + pcode;
    logger.info('第一次生成二维码');
    try {
      let a = await QRCodetorul.toDataURL(url);
      let filepath = await baseimgwrite(a, pcode + '.png', pcode);
      if (filepath.code) {
        return {
          code: 1,
          data: null,
          msg: '生成二维码异常,请联系客服'
        };
      } else {
        if (!isexist) {
          await qrcodeAdd({
            pcode: pcode,
            url: filepath.data.url,
            qrcodeurl: url
          });
        } else {
          await qrcodeUpdate({
            id: isexist.id,
            pcode: pcode,
            url: filepath.data.url
          });
        }
        return {
          code: 0,
          data: filepath.data.url,
          msg: '生成二维码成功'
        };
      }
    } catch (error) {
      logger.info(error)
      return {
        code: 1,
        data: null,
        msg: '生成二维码异常,请联系客服'
      };
    }
  } else {
    logger.info('已生成过二维码，直接返回');
    return {
      code: 0,
      data: isexist.url,
      msg: '已生成过二维码，直接返回'
    };
  }
}
// 查看海报
async function mybuildreport(pcode) {
  if (!pcode) {
    return {
      code: 1,
      msg: 'pcode不允许为空！'
    };
  }
  const isexist = await qrcodeQueryOne({ pcode: pcode });
  // if (!isexist || !isexist.report_url) {
    let url = wechat.qrcodeurl + pcode;
    logger.info('第一次生成海报');
    try {
      let a = await buildQrcode(url);
      let filepath = await baseimgwrite2(a, pcode + '_report.png', pcode);
      if (filepath.code) {
        return {
          code: 1,
          data: null,
          msg: '生成海报异常,请联系客服'
        };
      } else {
        if (!isexist) {
          await qrcodeAdd({
            pcode: pcode,
            report_url: filepath.data.url,
            qrcodeurl: url
          });
        } else {
          await qrcodeUpdate({
            id: isexist.id,
            pcode: pcode,
            report_url: filepath.data.url
          });
        }
        return {
          code: 0,
          data: filepath.data.url,
          msg: '生成海报成功'
        };
      }
    } catch (error) {
      logger.info(error)
      return {
        code: 1,
        data: null,
        msg: '生成海报异常,请联系客服'
      };
    }
  // } else {
  //   logger.info('已生成过海报，直接返回');
  //   return {
  //     code: 0,
  //     data: isexist.report_url,
  //     msg: '已生成过海报，直接返回'
  //   };
  // }
}

async function decodeBase64Image(dataString) {
  const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
  const response = {};

  if (matches.length !== 3) {
    return new Error('Invalid input string');
  }
  response.type = matches[1];
  response.data = new Buffer(matches[2], 'base64');



  var seed = crypto.randomBytes(20);
  var uniqueSHA1String = crypto
    .createHash('sha1')
    .update(seed)
    .digest('hex');
  const imageTypeDetected = matches[1].match(/\/(.*?)$/);


  response.name = `${uniqueSHA1String}.${imageTypeDetected[1]}`;
  return response;
}

async function baseimgwrite(base64Data, name, pcode) {
  var imageBuffer = await decodeBase64Image(base64Data);
  //验证图片类型；
  const userUploadedImagePath = path.join(process.cwd(), `/files/${pcode}.png`);
  fs.writeFile(userUploadedImagePath, imageBuffer.data,
    function () {
      logger.info('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
    });
  let result1 = await put_local({ filepath: userUploadedImagePath, name: name, pcode: pcode });
  fs.unlinkSync(userUploadedImagePath);
  return result1;
}
async function baseimgwrite2(base64Data, name, pcode) {
  //验证图片类型；
  const userUploadedImagePath = path.join(process.cwd(), `/files/${pcode}.png`);
  fs.writeFile(userUploadedImagePath, base64Data,
    function () {
      logger.info('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath);
    });
  let result1 = await put_local({ filepath: userUploadedImagePath, name: name, pcode: pcode });
  fs.unlinkSync(userUploadedImagePath);
  return result1;
}

async function subMsg_callback(doc) {
  logger.info('------subMsg_callback------doc-',doc)
  if (doc.errMsg == 'requestSubscribeMessage:ok') {
    let pcode = doc.pcode;
    let people = await ExecGetOne(`select openid from hzz_peoples where code ='${pcode}'`);
    let openid = people ? people.openid : null;
    doc = _.omit(doc, 'pcode', 'errMsg');
    for (const key in doc) {
      let newobj = {
        pcode: pcode,
        openid: openid,
        status: 0,
        isusing: 1
      };
      newobj.msgtmpid = key;
      newobj.type = doc[key];
      if (newobj.type == 'accept') {
        newobj.status = 1;
      }
      if (newobj.pcode && newobj.msgtmpid && newobj.type) {
        await msgsubscribeEdit(newobj);
      }
    }
  }
  return {
    code: 0,
    msg: '订阅状态保存成功'
  }
}
let msgType = {
  'realauth_tmpid': '实名认证',
  'recomreview_tmpid': '推荐人申请',
  'apppro_tmpid': '匹配进度通知',
  'daeay_tmpid': '每日推荐',
  'user_confirm': '新用户确认',
  'photo_tmpid': '相册解锁申请',
  'chat_tmpid': '聊天消息',
  'validate_info': '个人资料校验',
};
let msgtempOBJ = {
  'realauth_tmpid': 'SQdtjewo7sk9AJBYzpZHp5pYGUfBwqOmybSOs41nGuo',
  'recomreview_tmpid': 'dI_Oj7duZ1FrsduKd6wjP1ydQJQCy9APMxlL_SzH4kU',
  'apppro_tmpid': 'dI_Oj7duZ1FrsduKd6wjP1ydQJQCy9APMxlL_SzH4kU',
  'daeay_tmpid': 'SWboBLCXRQEUfglNtrVtkQoHU-b-_ooYFzo-8n-egso',
  'user_confirm': 'dI_Oj7duZ1FrsduKd6wjP1ydQJQCy9APMxlL_SzH4kU',
  'photo_tmpid': 'dI_Oj7duZ1FrsduKd6wjP1ydQJQCy9APMxlL_SzH4kU',
  'chat_tmpid': 'SWboBLCXRQEUfglNtrVtkQoHU-b-_ooYFzo-8n-egso',
  'validate_info': 'dI_Oj7duZ1FrsduKd6wjP1ydQJQCy9APMxlL_SzH4kU',
};
const sendMsg = async function (tmpid, data, pcode, openHtml, send_data_red) {
  try {
    let people = await peopleExecOne({ code: pcode }, 'phone,id,openid,name,nickname');
    let openid = null;
    let phone = people.phone;
    // 取用户微信公众号openid
    let usertoken = await QueryOne('hzz_usertokens', { pcode: pcode, openid: people.openid });
    if (usertoken && usertoken.unionid) {
      let wechatuser = await QueryOne('hzz_wechatusers', { unionid: usertoken.unionid, fllow: 1 });
      if (wechatuser && wechatuser.openid) {
        openid = wechatuser.openid;
      }
    }
    // 保存消息表记录
    let msgData = await messageAdd({
      pcode: pcode,
      openid: openid,
      phone: phone,
      template_id: wechat[tmpid],
      sendurl: wechat.sendMsgUrl,
      msg: JSON.stringify(data),
      type: msgType[tmpid]
    })
    // 用户关注公众号，则发送公众号消息
    if (openid) {
      logger.info('用户关注公众号，则发送公众号消息',openid)
      let body = {
        "touser": openid,
        "template_id": wechat[tmpid],
        "url": "http://weixin.qq.com/download",
        "miniprogram": {
          "appid": wechat.appid,
          "path": openHtml || wechat.openHtml
        },
        "data": data
      };
      body.miniprogram.path = body.miniprogram.path.split('/')[body.miniprogram.path.split('/').length - 1];
      let result = await SendWechatMsg(wechat.sendMsgUrl, body, 'wechat');
      if (result.errcode) {
        messageUpdate({ id: msgData.id, issend: 0, errmsg: result.errmsg, msg: JSON.stringify(body),sendurl: wechat.sendMsgUrl,openid:openid,"template_id": wechat[tmpid] });
        return {
          code: 1,
          msg: result.errmsg
        }
      } else {
        // 发送成功
        messageUpdate({ id: msgData.id, issend: 1, errmsg: result.errmsg, msg: JSON.stringify(body),sendurl: wechat.sendMsgUrl,openid:openid,"template_id": wechat[tmpid] });
        return {
          code: 0,
          msg: '发送订阅消息成功'
        }
      }
    } else {
      logger.info(`用户没有关注公众号，发送小程序通知消息,pcode=${pcode},msgtmpid=${msgtempOBJ[tmpid]}`);
      // 用户没有关注公众号，发送小程序通知消息
      let sendURL = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s';
      let usertoken = await QueryOne('hzz_msgsubscribes', { pcode: pcode, msgtmpid: msgtempOBJ[tmpid], type: 'accept', isusing: 1 });
      if (usertoken) {
        let body = {
          "touser": usertoken.openid,
          "template_id": msgtempOBJ[tmpid],
          "page": 'pages/index/index',//+ openHtml,
          "miniprogram_state": wechat.miniprogram_state,
          "lang": "zh_CN",
          "data": send_data_red
        }
        let result = await SendWechatMsg(sendURL, body, 'redspider');
        if (result.errcode) {
          messageUpdate({ id: msgData.id, issend: 0, errmsg: result.errmsg, msg: JSON.stringify(body),sendurl: sendURL ,openid:usertoken.openid,"template_id": msgtempOBJ[tmpid]});
          return {
            code: 1,
            msg: result.errmsg
          }
        } else {
          // 发送成功
          messageUpdate({ id: msgData.id, issend: 1, errmsg: result.errmsg, msg: JSON.stringify(body),sendurl: sendURL ,openid:usertoken.openid,"template_id": msgtempOBJ[tmpid]});
          return {
            code: 0,
            msg: '发送订阅消息成功'
          }
        }
      } else {
        logger.error('sendMsg--该用户尚未订阅消息，发送失败--');
        return {
          code: 1,
          msg: '该用户尚未订阅消息，发送失败'
        }
      }
    }
  } catch (error) {
    logger.error('sendMsg--发送订阅消息,获取access_token异常--', error);
    return {
      code: 1,
      msg: '发送订阅消息异常'
    }
  }
}
// // 未成功发送消息，定时重发
// const messageTimerSend = async function () {
//   let list = await Exec(`select * from hzz_messages where issend=0 and openid is not null and createtime >'${formatDate(new Date())}';`);
//   for (let index = 0; index < list.length; index++) {
//     const data = list[index];
//     if (data.openid) {
//       wechatSendMsg(data, data.msg);
//     }
//   }
// }
// const wechatSendMsg = async function (data, body) {
//   let result = await sendMsg(data.sendurl, body);
//   if (result && result.code) {
//     logger.info('sendMsg--发送订阅消息,未获取到access_token');
//     messageUpdate({ id: data.id, issend: 0, errmsg: '未获取到access_token' });
//     return {
//       code: 1,
//       msg: '发送订阅消息失败，未获取到access_token'
//     }
//   } else {
//     if (result && result.errcode == 0) {
//       // 发送成功
//       logger.error('wechatSendMsg--定时发送订阅消息成功:', result);
//       messageUpdate({ id: data.id, issend: 1, errmsg: result.errmsg, msg: JSON.stringify(body) });
//     } else {
//       messageUpdate({ id: data.id, issend: 0, errmsg: result.errmsg, msg: JSON.stringify(body) });
//       // 发送失败
//       logger.error('wechatSendMsg--定时发送订阅消息失败，errmsg:', result);
//     }
//   }
// }

async function getMsgTmpList() {
  try {
    let datass = MYSQL_CONF.database;
    let result;
    if (datass == 'hzzdb') {
      result = await requestGet("https://apiv2.spiderslove.com/api/wechat/getMessageTmpList");
    } else {
      let access_token_data = await getToken('redspider');
      if (!access_token_data.code) {
        // 格式化请求地址
        var getMsgTmpList_url = util.format(wechat.getMsgTmpList, access_token_data.data);
        let rData = await requestGet(getMsgTmpList_url);
        if (rData && rData.data && rData.data.length > 0) {
          result = {
            code: 0,
            data: rData.data,
            msg: '获取成功'
          }
        } else {
          result = {
            code: 1,
            msg: '获取消息模板失败，请联系客服'
          }
        }
      }
    }
    return result;
  } catch (error) {
    logger.error('sendMsg--发送订阅消息,获取access_token异常--', error);
    return {
      code: 1,
      msg: '获取消息模板异常，请联系客服'
    }
  }
}

async function msgIsNeedRead(pcode) {
  try {
    if (!pcode) {
      return {
        code: 1,
        msg: 'pcode不允许为空！'
      };
    }
    let result = await msgsubscribeIsRead(pcode);
    return {
      code: 0,
      data: result
    }
  } catch (error) {
    logger.info('msgIsNeedRead', error);
    return {
      code: 0,
      data: true
    }
  }
}
// 后台手动发送消息
async function sendMsg_hand(doc) {
  try {
    logger.info('后台手动发送消息-sendMsg_hand,doc',doc)
    let { pcode, content, remarks } = doc;
    if (!pcode) {
      return {
        code: 1,
        msg: 'pcode参数未传'
      }
    }
    let send_data = {
      "first": {
        "value": '您好，您的业务有新进展！',
        "color": "#173177"
      },
      "keyword1": {
        "value": "客服消息",
        "color": "#173177"
      },
      "keyword2": {
        "value": content,
        "color": "#74BB44"
      },
      "remark": {
        "value": "此消息无需回复，感谢您的支持！",
        "color": "#173177"
      }
    };
    let send_data_red = {
      "thing2": {
        "value": `客服消息：${content}`
      },
      "time1": {
        "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
      }
    };
    return sendMsg('apppro_tmpid', send_data, pcode,"pages/index/index", send_data_red);
  } catch (error) {
    logger.error('sendMsg_hand--后台手动推荐消息异常', error);
    return {
      code: 1,
      msg: '发送消息异常'
    }
  }
}

// 举荐某人
const peopleRecommend = async function (doc) {
  try {
    logger.info(`-------peopleRecommend------doc:`, doc)
    if (!doc.pcode) {
      return {
        code: 1,
        msg: 'pcode参数缺失'
      }
    }
    // 更新用户排序
    let peo = await QueryOne('hzz_peoples', { code: doc.pcode }, 'id,isopen,online');
    if (!peo.online) {
      return {
        code: 1,
        msg: '推荐失败，用户未发布'
      }
    }
    await Update('hzz_peoples', { id: peo.id, sortnum: 1, topstate: 1, updatetime: new Date() });
    // 发送推荐消息
    // peopleRecom(doc.pcode);
    return {
      code: 0,
      msg: '推荐成功，明日会优先推荐'
    }
  } catch (error) {
    logger.info(`-------peopleRecommend------error:`, error)
    return {
      code: 1,
      msg: error ? error.message : '推荐失败'
    }
  }
}
// 每日提醒
const sendmsg_auto = async function () {
  try {
    let list = await Exec(`select code from hzz_peoples where block =0 and openid IS NOT NULL  ;`);//OR phone IS NOT NULL)
    let send_data = {
      "first": {
        "value": "您好，您的业务有新进展！",
        "color": "#173177"
      },
      "keyword1": {
        "value": "每日推荐",
        "color": "#173177"
      },
      "keyword2": {
        "value": `今日推荐已更新，快去看看是谁吧！`,
        "color": "#173177"
      },
      "remark": {
        "value": "点击查看详情",
        "color": "#173177"
      }
    };
    let send_data_red = {
      "thing1": {
        "value": "每日推荐"
      },
      "thing3": {
        "value": "今日推荐已更新，快去看看是谁吧！"
      },
      "thing4": {
        "value": "点击查看详情"
      },
      "time2": {
        "value": moment(new Date()).format('YYYY-MM-DD HH:mm')
      }
    };
    for (const item of list) {
      sendMsg('daeay_tmpid', send_data, item.code, "pages/index/index", send_data_red);
    }
  } catch (error) {
    logger.error('sendMsg_hand--后台自动发送推荐消息异常', error);
  }
}

async function getOfficial(tokenData) {
  let { unionid, openid } = tokenData;
  if (!unionid) {
    unionid = await getUserUnionid(openid);
  }
  let isOff = await isOfficial(unionid);
  logger.info('getOfficial--获取用户关注公众号状态', tokenData, isOff);
  return isOff;
}

async function initUnionID(oid) {
  var timestamp = new Date().getTime() + '';
  let list = await queryUserList(oid);
  if (list && list.length) {
    // 先更新所有用户未为订阅状态
    for (let i = 0; i < list.length; i++) {
      const openid = list[i];
      let userinfo = await queryUserInfo(openid);
      if (userinfo && userinfo.subscribe) {
        let uinondata = await wechatuserQuery(openid);
        if (uinondata) {
          uinondata.fllow = userinfo.subscribe;
          uinondata.timestamp = userinfo.timestamp;
          await wechatuserUpdate(uinondata);
        } else {
          await wechatuserAdd({
            openid: openid,
            unionid: userinfo.unionid,
            fllow: userinfo.subscribe,
            timestamp: timestamp
          });
        }
      } else {
        console.log('未找到unionid')
      }
    }
    //  同步完之后给未订阅用户设置为未订阅
    await Exec(`update hzz_wechatusers set fllow =0 where timestamp<>${timestamp}`);
    logger.info('同步用户公众号关注状态成功', new Date());
  } else {
    logger.info('----initUnionID---', list);
  }
}
// 公众号关注取消回调
const Token = 'redspider';
const EncodingAESKey = '7lteoERHpFX3uC1OTqe7rJcbe5PqADjIWug7vV8C47V';
async function wx_sub_callback(req) {
  logger.info('--公众号关注取消回调------wx_sub_callback-,req', req.query)
  let { signature, timestamp, echostr } = req.query;
  if (echostr) {
    return echostr;
  }
}
async function wx_sub_callback_val(req) {
  let query = url.parse(req.url).query;
  logger.info('--公众号关注取消回调------wx_sub_callback_val-,query', query)
  let params = qs.parse(query);
  logger.info('--公众号关注取消回调------wx_sub_callback_val-,params', params)
  if (Signature(params, Token)) {
    return params.echostr;
  } else {
    return 'signature fail';
  }
}
function Signature(params, token) {
  let key = [token, params.timestamp, params.nonce].sort().join('');
  let sha1 = crypto.createHash('sha1').update(key).digest('hex');
  logger.info('--公众号关注取消回调-----Signature:sha1:::', sha1)
  return sha1 === params.signature;
}
async function getUserOfficial(pcode) {
  try {
    let tokenData = await usertokenGetInfo(pcode)
    let { unionid, openid } = tokenData;
    if (!unionid) {
      unionid = await getUserUnionid(openid);
    }
    let isOff = await isOfficial(unionid);
    logger.info('getUserOfficial--获取用户关注公众号状态', tokenData, isOff);
    return {
      pcode: pcode,
      isOfficial: isOff
    };
  } catch (error) {
    logger.error('getUserOfficial--获取用户关注公众号状态', tokenData, isOff);
    return {
      pcode: pcode,
      isOfficial: 0
    };
  }
}

module.exports = {
  getToken,
  getOpenid,
  decodeDataInfo,
  mybuildqrcode,
  mybuildreport,
  subMsg_callback,
  sendMsg,
  // messageTimerSend,
  getMsgTmpList,
  msgIsNeedRead,
  // wechatSendMsg,
  sendMsg_hand,
  peopleRecommend,
  sendmsg_auto,
  initUnionID,
  wx_sub_callback_val,
  wx_sub_callback,
  First,
  getUserOfficial
}